import { login, logout, getInfo } from '@/api/user'
// eslint-disable-next-line no-unused-vars
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
import getQueryString from '@/utils/getCookies'
const getCookies = getQueryString.getCookie
import { Message } from 'element-ui'

const getDefaultState = () => {
  return {
    token: getToken(),
    username: '',
    avatar: ''
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, username) => {
    state.username = username
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  CLEAR_TOKEN: () => {
    state.username = ''
    state.token = ''
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(response => {
        if (response.code === 200 && response.data === 0 ) {
          // commit('SET_TOKEN', data.token)
          commit('SET_NAME', getCookies('username'))
          // setToken(data.token)
          resolve()
        } else {
          Message.error(response.msg)
        }
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        // removeToken() // 如果是 token，则需要首先remove，退出登录，后端删除cookie
        resetRouter()
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 后端删除cookie，此处不做处理
  resetToken({ commit }) {
    return new Promise(resolve => {
      // removeToken() // 如果是 token，则需要首先remove
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

